package cqupt.spark_log.fileio;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import cqupt.spark_log.contrant.Contant;

public class FileWriteMan {
	private FileWriter fileWriter = null;
	private BufferedWriter bufferedWriter = null;

	public FileWriteMan() {
		try {
			this.fileWriter = new FileWriter(Contant.BASE_PATH + "/" + Contant.APP_NAME);
			this.bufferedWriter = new BufferedWriter(this.fileWriter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public FileWriteMan(String name) {
		try {
			this.fileWriter = new FileWriter(Contant.BASE_PATH + name);
			this.bufferedWriter = new BufferedWriter(this.fileWriter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * basepath回溯n个目录，可以自定义增加这个目录下的name目录
	 * @param n
	 * @param name
	 */
	public FileWriteMan(int n,String path,String name) {
		try {
			StringBuilder stringBuilder = new StringBuilder(Contant.BASE_PATH);
			for (int i=0; i<n; i++) {
				stringBuilder.delete(stringBuilder.lastIndexOf("/"), stringBuilder.length());
			}
			name = name == null? "": name;
			File file = new File(stringBuilder.toString() + path);
			if (!file.exists()) {
				file.mkdirs();
			}
			this.fileWriter = new FileWriter(stringBuilder.toString() + path + "/" + name);
			this.bufferedWriter = new BufferedWriter(this.fileWriter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void insertLine(String line, boolean newLine) {
		try {
			bufferedWriter.write(line);
			if (newLine) {
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void insertLine(String line) {
		insertLine(line, true);
	}

	public void close() {
		try {
			bufferedWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
